package com.aboo.service;

import com.aboo.po.User;
import com.aboo.vo.ReturnVO;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Slf4j
@Component
public class RUserService {

    @Resource
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "addFallback")
    public ReturnVO<User> add(User user) {
        HttpHeaders httpHeaders = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        httpHeaders.setContentType(type);
        HttpEntity<User> objectHttpEntity = new HttpEntity<>(user, httpHeaders);

        String url = "http://eureka-client-one/user/add";
        ReturnVO<User> rv = restTemplate.postForObject(url, objectHttpEntity, ReturnVO.class);
        return rv;
    }

    public ReturnVO<User> addFallback(User user) {
        log.warn("RestTemplate网络不好，熔断...");
        ReturnVO<User> rv = new ReturnVO<>();
        rv.setCode("001");
        rv.setMsg("网络不好");
        return rv;
    }

    @HystrixCommand(fallbackMethod = "editFallback")
    public ReturnVO<User> edit(User user) {
        String url = "http://eureka-client-one/user/edit";
        ReturnVO<User> rv = restTemplate.postForObject(url, user, ReturnVO.class);
        return rv;
    }

    public ReturnVO<User> editFallback(User user) {
        log.warn("RestTemplate网络不好，熔断...");
        ReturnVO<User> rv = new ReturnVO<>();
        rv.setCode("001");
        rv.setMsg("网络不好");
        return rv;
    }

}
